<template>
	<com-image
	:src="url"
	:mode="mode"
	:lazyLoad="lazyLoad"
	:bgColor="bgColor"
	:borderRadius="borderRadius"
	:borderTopLeftRadius="borderTopLeftRadius"
	:borderTopRightRadius="borderTopRightRadius"
	:borderBottomRightRadius="borderBottomRightRadius"
	:borderBottomLeftRadius="borderBottomLeftRadius"
	:tipSize="tipSize"
	:tipColor="tipColorSync"
	:referer="referer"
	:enablePreview="enablePreview"
	:showPreviewBtn="showPreviewBtn"
	:enableRefresh="enableRefresh"
	@error="handleError">
		<template #error v-if="errorName">
			<com-icon :name="errorName" :size="tipSize + 10" :color="tipColorSync"></com-icon>
		</template>
	</com-image>
</template>

<script>
	import { downloadNetResourceSaveLocal, base64ImageToLocalImage } from '@/assets/js/native.js'
	import { suffix, randomId } from '@/assets/js/util.js'
	import SkinColor from '@/assets/skin/index.js'
	export default {
		props: {
			//图片链接
			src: {
				type: String,
				default: ''
			},
			//裁剪模式
			mode: {
				type: String,
				default: ''
			},
			//懒加载
			lazyLoad: {
				type: Boolean,
				default: false
			},
			//背景色
			bgColor: {
				type: String,
				default: ''
			},
			//圆角大小
			borderRadius: {
				type: [Number,String],
				default: 0
			},
			borderTopLeftRadius: {
				type: [Number,String],
				default: 0
			},
			borderTopRightRadius: {
				type: [Number,String],
				default: 0
			},
			borderBottomRightRadius: {
				type: [Number,String],
				default: 0
			},
			borderBottomLeftRadius: {
				type: [Number,String],
				default: 0
			},
			//提示文字大小
			tipSize: {
				type: [String, Number],
				default: 30
			},
			//提示文字颜色
			tipColor: {
				type: String,
				default: ''
			},
			//来源
			referer: {
				type: String,
				default: ''
			},
			//解密
			decrypt: {
				type: String,
				default: ''
			},
			//开启点击预览功能
			enablePreview: {
				type: Boolean,
				default: false
			},
			//显示预览按钮
			showPreviewBtn: {
				type: Boolean,
				default: false
			},
			//开启错误刷新按钮
			enableRefresh: {
				type: Boolean,
				default: false
			}
		},
		computed: {
			skinMode () {
				return this.$store.getters['setting/GET_SKIN_MODE']
			},
			skinColor () {
				return SkinColor[this.skinMode]
			},
			network () {
				return this.$store.getters['network/GET']
			},
			globalConfig () {
				return this.network?.source?.globalConfig || {}
			},
			tipColorSync () {
				return this.tipColor || this.skinColor.color_1
			}
		},
		data() {
			return {
				url: '',
				errorTime: 0,//错误加载次数
				errorName: '',//错误提示图标
				isCache: false//是否加载过缓存了
			}
		},
		created() {
			this.url = this.parseSrc(this.src)
		},
		methods: {
			//处理图片域名
			parseSrc (src) {
				if ( !src ) return ''
				const baseUrl = this.network.baseUrl
				return src.startsWith('data:image') || src.startsWith('http') ? src : baseUrl + src
			},
			handleError(e) {
				//查看图片是否有缓存
				const caches = this.$store.getters['cache/GET']
				const index = caches.findIndex(cache => cache.origin == this.src)
				//如果有缓存
				if ( index > -1 ) {
					//判断是否加载过缓存了，如果加载过了缓存，还报错，说明缓存路径已经失效了，需要重新加载
					if ( !this.isCache ) {
						this.errorName = 'file'
						this.url = caches[index].path
						this.isCache = true
						return
					} else {
						//删除已失效的缓存路径
						this.$store.dispatch('cache/remove', this.src)
					}
				}
				this.errorTime++
				//第一次加载错误，尝试获取图片解密方法
				const decrypt = this.decrypt || this.globalConfig.imageDecrypt
				if ( this.errorTime == 1 && this.src && decrypt ) {
					this.errorName = 'unlock'
					this.network.$text(decrypt, this.src, null).then(url => {
						if ( url.startsWith('data:image') ) {
							const format = url.match(/data:image\/*([\s\S]*?);base64,/)[1]
							const fileName = randomId() + '.' + (format || suffix(this.src))
							base64ImageToLocalImage(url, fileName).then(path => {
								this.url = path
								//将图片路径存入缓存
								this.$store.dispatch('cache/add', {
									origin: this.src,
									path
								})
							}).catch(err => {
								this.handleError(e)
							})
						} else if ( url ) {
							this.url = url
							this.$store.dispatch('cache/add', {
								origin: this.src,
								path: url
							})
						} else {
							this.handleError()
						}
					})
				} else this.errorTime++
				//第二次加载错误，尝试下载图片放在本地显示，因为加载错误可能是图片有防盗链的缘故
				if ( this.errorTime == 2 && this.src ) {
					this.errorName = 'down'
					const referer = this.referer ? this.referer : this.globalConfig.imageReferer ? this.globalConfig.imageReferer : this.network.baseUrl//获取图片referer
					downloadNetResourceSaveLocal({
						src: this.src,
						referer: referer,
						format: 'png',
						complete: res => {
							if ( res.errCode == 0 ) {
								this.url = res.tempFilePath
								//将图片路径存入缓存
								this.$store.dispatch('cache/add', {
									origin: this.src,
									path: res.tempFilePath
								})
							} else {
								this.errorText = ''
							}
						}
					})
				}
			}
		},
		watch: {
			src (newVal) {
				this.url = this.parseSrc(newVal)
			}
		}
	}
</script>

<style>
	/* #ifndef APP-NVUE */
	.com-image-item {
		width: 100%;
		flex-shrink: 0;
	}
	/deep/ .com-image-item > div {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
	}
	/* #endif */
	.com-image .preview-btn {
		width: 40rpx;
		height: 40rpx;
		border-radius: 40rpx;
	}
</style>
